import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { message, Spin, Empty, Card } from "antd";
import { getPostListApi } from "@/apis/post.ts";
import PostCard from "@/components/postCard";
import style from "./index.module.css";
import PostButton from "@/components/post";

export default function Community() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [postList, setPostList] = useState([]);

  // 获取帖子列表
  const getPostList = async () => {
    try {
      setLoading(true);
      const res: any = await getPostListApi({ page: 1, size: 30 });
      if (res.code === 0) {
        setPostList(res.data.records);
      } else {
        message.error(res.message || "获取帖子列表失败");
      }
    } catch (error) {
      message.error("获取帖子列表失败");
    } finally {
      setLoading(false);
    }
  };

  const handlePost = (post: any) => {
    navigate(`/community/post_info/${post.id}`);
  };

  useEffect(() => {
    getPostList();
  }, []);

  return (
    <div className={style.communityContainer}>
      <Card className={style.headerCard}>
        <div className={style.header}>
          <h1 className={style.title}>社区</h1>
          <p className={style.subTitle}>
            欢迎来到社区，分享你的想法和经验，发现有趣的内容 😊
          </p>
        </div>
      </Card>

      <Spin spinning={loading}>
        {postList.length > 0 ? (
          <div className={style.postList}>
            {postList.map((item: any) => (
              <PostCard
                key={item.id}
                post={item}
                onClick={() => handlePost(item)}
              />
            ))}
          </div>
        ) : (
          <Empty
            description="暂无帖子，快来发布第一个吧！"
            styles={{
              image: {
                width: 100,
                height: 100,
                margin: "0 auto",
              },
            }}
          />
        )}
      </Spin>
      <PostButton refreshPostList={getPostList} />
    </div>
  );
}
